package com.threegroup.admin.security.user;

import com.threegroup.admin.entity.SysUserEntity;
import com.threegroup.common.entity.UserEntity;
import com.threegroup.common.enums.EStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public final class SecurityUserFactory {

    private SecurityUserFactory() {
    }

    /**
     * 通过管理员Admin，生成一个SpringSecurity用户
     *
     * @param admin
     * @return
     */
    public static SecurityUser create(SysUserEntity admin) {
        boolean enabled = admin.getStatus() == EStatus.ENABLE;
        return new SecurityUser(
                admin.getId(),
                admin.getUsername(),
                admin.getPassword(),
                admin.getSuperAdmin(),
                admin.getDeptId(),
                admin.getRole(),
                enabled,
                mapToGrantedAuthorities(admin.getPermissionList())
//                mapToGrantedAuthorities(new ArrayList<>())
        );
    }

    /**
     * 通过用户User，生成一个SpringSecurity用户
     * @param user
     * @return
     */
//    public static SecurityUser create(UserEntity user) {
//        boolean enabled = user.getStatus() == EStatus.ENABLE;
//        return new SecurityUser(
//                user.getId(),
//                user.getName(),
//                user.getPhone(),
//                0,
//                null,
//                enabled,
//                mapToGrantedAuthorities(new ArrayList<String>())
//        );
//    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(List<String> authorities) {
        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

}
